/*
tangjx
2018.10.23
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "factorydatamaneger.h"

#define SUCCESS 0
#define FAIL -1

CFactoryDataManager::CFactoryDataManager()
{
    mVersion = 1;
    mCloudType = 0;
    mMenuCloudType = 0;
    mCrc = 0;
    
    char Data[8] = {0};
    if(ReadFromConfigFile(&Data) != 0)
    {
        Data[7] = 1;
        Data[1] = CheckCRC16(Data,6) & 0xFF00;
        Data[0] = CheckCRC16(Data,6) & 0x00FF;
        Write2ConfigFile(Data);
    }
    
    PrintHex(Data);
    
    mVersion = Data[7] << 16 + Data[6];
    mCloudType = Data[5] << 16 + Data[4];
    mMenuCloudType = Data[3] << 16 + Data[2];
    mCrc = Data[1] << 16 + Data[0];
    printf("mVersion:%d mCloudType:%d mMenuCloudType:%d mCrc:%02X%02X\n",mVersion,mCloudType,mMenuCloudType,Data[1],Data[0]);
    
    if(mCrc != CheckCRC16(Data,6)) mBreakFlag = ture;
}

CFactoryDataManager::~CFactoryDataManager() {}

int CFactoryDataManager::FactoryDataUpdate(char* Data, int Size)
{
    if(Size != 8 || Data == NULL) return -1;
    
    int nVersion = Data[7] << 16 + Data[6];
    int nCloudType = Data[5] << 16 + Data[4];
    int nMenuCloudType = Data[3] << 16 + Data[2];
    int nCrc = Data[1] << 16 + Data[0];
    
    if(nCrc != CheckCRC16(Data, Size - 2)) return -2;
    
    if(mBreakFlag || nVersion > mVersion) return Write2ConfigFile(Data);
    
    return FAIL;
}

unsigned int CFactoryDataManager::CheckCRC16(char* Data, int Size)
{
    unsigned int nCrc = 0;
    int nBitsRead = 0;
    int nBitFlag = 0;
    
    if(Size <= 0 || Data == NULL) return 0;
    
    while(Size > 0)
    {
        nBitFlag = nCrc >> 15;
        
        nCrc <<=1;
        nCrc |= (*Data >> (7 - nBitsRead)) & 1;
        
        nBitsRead++;
        if(nBitsRead > 7)
        {
            nBitsRead=0;
            Data++;
            Size--;
        }
        
        if(nBitFlag) nCrc ^= 0x8005;
    }
    
    return nCrc;
}

int CFactoryDataManager::ReadFromConfigFile(char* Buff)
{
    FILE *fdlogDataFile = fopen("./FactoryConfig.ini", "r");
	if(NULL != mlogDataFile)
	{
		fread(Buff, 8, 1, fdlogDataFile);
		printf("buff:\n%s\n",Buff);
		fclose(fdlogDataFile);
		return SUCCESS;
	}
	printf("open file failed\n");
	return FAIL;
}

Void CFactoryDataManager::Write2ConfigFile(char* Data)
{
    FILE *fdlogDataFile = fopen("./FactoryConfig.ini", "w+");
	if(NULL != mlogDataFile)
	{
		fwrite(Data, 8, 1, fdlogDataFile);
		fclose(fdlogDataFile);
		return SUCCESS;
	}
	printf("open file failed\n");
	return FAIL;
}

Void CFactoryDataManager::PrintHex(char* Data)
{
    printf("Data:\n");
    for(int i=1;i<=strlen(Data);i++)
    {
        printf("%02X ",Data[strlen(Data)-i]);
    }
    printf("\n");
}











